package com.roger.springcloudGreenwich.service.impl;

import com.roger.springcloudGreenwich.config.DistributedRedisLock;
import com.roger.springcloudGreenwich.service.LockService;
import lombok.extern.slf4j.Slf4j;
import org.redisson.api.RLock;
import org.redisson.api.RedissonClient;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.Collections;
import java.util.List;
import java.util.concurrent.TimeUnit;


@Service
@Slf4j
public class LockServiceImpl implements LockService {

    static Integer ticketNum;
    static
    {
        ticketNum = 500;
    }

    @Autowired
    DistributedRedisLock distributedRedisLock;

    @Override
    public void buyTicket(Integer id) {
        String LOCK = "myLock:" + id;
        String threadName = Thread.currentThread().getName();

        try {
            log.info("{}开始抢票",threadName + " 开始抢票");
            if(distributedRedisLock.lock(LOCK)){
                if(ticketNum == 0){
                    log.error("{}抢票失败，余额不足",threadName);
                    return;
                }

                TimeUnit.SECONDS.sleep(5);

                ticketNum--;
                log.info("{}抢到一张票,还有{}张",threadName,ticketNum);
            }else{
                log.error("{}获取锁失败", threadName);
            }

        }catch (Exception e){
            e.printStackTrace();
            log.error("{}", e);
        }finally {
            distributedRedisLock.releaseLock(LOCK);
        }
    }


    public static void main(String[] args) {
        List<String> list = new ArrayList();
        list.add("/lock2/0000003320");
        list.add("/lock2/0000003322");
        list.add("/lock2/0000003321");
        list.add("/lock2/0000003323");
        System.out.println("before:"+ list);
        Collections.sort(list);
        System.out.println("after" + list);
        before("/lock2/0000003321", list);

    }

    static void before(String current, List<String> list){
        int index = list.indexOf(current) - 1;
        System.out.println(list.get(index));
    }


}
